//
//  UPAddressPickerView.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/27.
//

#import "UPAddressPickerView.h"

@interface UPAddressPickerViewConfig : NSObject

@property (nonatomic, copy) NSString *provincePlaceholder;
@property (nonatomic, copy) NSString *cityPlaceholder;
@property (nonatomic, copy) NSString *separatorText;
@property (nonatomic, strong) UIColor *placeholderColor;
@property (nonatomic, strong) UIColor *selectedColor;
@property (nonatomic, strong) UIColor *selectedBackgroundColor;

@end

@implementation UPAddressPickerViewConfig

- (instancetype)init {
    self = [super init];
    if (self) {
        _provincePlaceholder = @"";
        _cityPlaceholder = [NSString stringWithFormat:@"  %@  ", LocalizableForKey(@"Choose")];
        _separatorText = @"";
        _placeholderColor = [UIColor colorWithHexString:@"#FFFFFF"];
        _selectedColor = [UIColor colorWithHexString:@"#000000"];
        _selectedBackgroundColor = [[UIColor colorWithHexString:@"#42714A"] colorWithAlphaComponent:0.1];
    }
    return self;
}

@end

@interface UPDataItem ()

@property (nonatomic, assign) BOOL isLeaf;

@end

@implementation UPDataItem

- (instancetype)initWithId:(NSString *)itemId name:(NSString *)name children:(NSArray<UPDataItem *> *)children {
    self = [super init];
    if (self) {
        _itemId = [itemId copy];
        _name = [name copy];
        _children = children;
        _isLeaf = (children == nil || children.count == 0);
    }
    return self;
}

@end

@interface UPAddressPickerView () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UPAddressPickerViewConfig *config;
@property (nonatomic, strong) NSArray<UPDataItem *> *dataSource;
@property (nonatomic, strong) NSMutableArray<UPDataItem *> *selectedPath;
@property (nonatomic, strong) NSArray<UPDataItem *> *currentLevelData;

@property (nonatomic, strong) UIScrollView *pathScrollView;
@property (nonatomic, strong) UIStackView *pathStackView;
@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *confirmButton;

@end

@implementation UPAddressPickerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.backgroundColor = [UIColor clearColor];
    _config = [[UPAddressPickerViewConfig alloc] init];
    _selectedPath = [NSMutableArray array];
    _maxLevel = 3;
    
    [self setupUI];
    [self setupConstraints];
}

- (void)setupUI {
//    [self addSubview:self.titleLabel];
    [self addSubview:self.confirmButton];
    [self addSubview:self.pathScrollView];
    [self.pathScrollView addSubview:self.pathStackView];
    [self addSubview:self.tableView];
}

- (void)setupConstraints {
//    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.trailing.equalTo(self).inset(16);
//        make.top.equalTo(self).offset(30);
//        make.height.equalTo(@20);
//    }];
    
    [self.pathScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(20);
        make.leading.trailing.equalTo(self).inset(30);
        make.height.equalTo(@31);
    }];
    
    [self.pathStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.pathScrollView).insets(UIEdgeInsetsMake(0, 16, 0, 16));
        make.height.equalTo(self.pathScrollView);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pathScrollView.mas_bottom).offset(8);
        make.leading.trailing.equalTo(self).inset(16);
        make.bottom.equalTo(self.confirmButton.mas_top).offset(-20);
    }];

    UIImage *buttonImage = [UIImage imageNamed:@"button_bg_style1"];
    CGFloat buttonHeight = 50.0;
    CGFloat buttonAspectRatio = buttonImage.size.width / buttonImage.size.height;
    CGFloat buttonWidth = buttonHeight * buttonAspectRatio;
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.height.mas_equalTo(buttonHeight);
        make.width.mas_equalTo(buttonWidth);
        make.bottom.equalTo(self).offset(-30);
    }];
}

#pragma mark - Public Methods

- (void)loadCountryAddress:(ADRLapidantModel *)address {
    self.dataSource = [self convertToDataItems:address];
    [self resetToFirstLevel];
}

- (void)resetSelection {
    [self resetToFirstLevel];
}

- (NSArray<UPDataItem *> *)getSelectedPath {
    return [self.selectedPath copy];
}

#pragma mark - Private Methods

- (NSArray<UPDataItem *> *)convertToDataItems:(ADRLapidantModel *)address {
    NSMutableArray *items = [NSMutableArray array];
    for (ADRCircumibilityModel *circumibility in address.circumibility) {
        [items addObject:[self convertCircumibilityToDataItem:circumibility]];
    }
    return [items copy];
}

- (UPDataItem *)convertCircumibilityToDataItem:(ADRCircumibilityModel *)circumibility {
    NSMutableArray *children = [NSMutableArray array];
    for (ADRBotanwiseModel *botanwise in circumibility.botanwise) {
        [children addObject:[self convertBotanwiseToDataItem:botanwise]];
    }
    return [[UPDataItem alloc] initWithId:circumibility.lotfication ?: @""
                                     name:circumibility.quindecimlocalety ?: @""
                                 children:[children copy]];
}

- (UPDataItem *)convertBotanwiseToDataItem:(ADRBotanwiseModel *)botanwise {
    NSMutableArray *children = [NSMutableArray array];
    for (ADRBotanwiseSubModel *subBotanwise in botanwise.botanwise) {
        [children addObject:[self convertSubBotanwiseToDataItem:subBotanwise]];
    }
    return [[UPDataItem alloc] initWithId:botanwise.lotfication ?: @""
                                     name:botanwise.quindecimlocalety ?: @""
                                 children:[children copy]];
}

- (UPDataItem *)convertSubBotanwiseToDataItem:(ADRBotanwiseSubModel *)subBotanwise {
    return [[UPDataItem alloc] initWithId:subBotanwise.lotfication ?: @""
                                     name:subBotanwise.quindecimlocalety ?: @""
                                 children:nil];
}

- (void)resetToFirstLevel {
    [self.selectedPath removeAllObjects];
    self.currentLevelData = self.dataSource;
    [self updatePathDisplay];
    [self.tableView reloadData];
}

- (void)updatePathDisplay {
    // 清除旧视图
    for (UIView *view in self.pathStackView.arrangedSubviews) {
        [self.pathStackView removeArrangedSubview:view];
        [view removeFromSuperview];
    }
    
    // 添加所有已选择的路径项
    for (NSInteger index = 0; index < self.selectedPath.count; index++) {
        UPDataItem *item = self.selectedPath[index];
        if (index > 0) {
            [self addSeparator];
        }
        [self addSelectedPathItemWithText:item.name level:index];
    }
    
    // 如果不是最后一级，添加下一级的占位项
    if (self.selectedPath.count < self.maxLevel) {
        if (self.selectedPath.count > 0) {
            [self addSeparator];
        }
        NSString *placeholderText = self.selectedPath.count == 0 ? self.config.provincePlaceholder : self.config.cityPlaceholder;
        [self addPlaceholderItemWithText:placeholderText];
    }
    
    // 添加弹性空间
    UIView *spacer = [[UIView alloc] init];
    [self.pathStackView addArrangedSubview:spacer];
    [spacer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.greaterThanOrEqualTo(@0);
    }];
    
    // 滚动到最后
    dispatch_async(dispatch_get_main_queue(), ^{
        CGFloat rightOffset = MAX(0, self.pathStackView.frame.size.width - self.pathScrollView.bounds.size.width + 16);
        [self.pathScrollView setContentOffset:CGPointMake(rightOffset, 0) animated:YES];
    });
}

- (void)addSeparator {
    UILabel *separator = [[UILabel alloc] init];
    separator.text = self.config.separatorText;
    separator.font = [UIFont systemFontOfSize:14];
    separator.textColor = [UIColor clearColor];
    [self.pathStackView addArrangedSubview:separator];
}

- (void)addSelectedPathItemWithText:(NSString *)text level:(NSInteger)level {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:text forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    [button setTitleColor:self.config.selectedColor forState:UIControlStateNormal];
    button.contentEdgeInsets = UIEdgeInsetsMake(6, 12, 6, 12);
    button.backgroundColor = self.config.selectedBackgroundColor;
    button.layer.cornerRadius = 15.5;
    button.tag = level;
    [button addTarget:self action:@selector(pathItemTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.pathStackView addArrangedSubview: button];
}

- (void)addPlaceholderItemWithText:(NSString *)text {
    UILabel *label = [[UILabel alloc] init];
    label.text = text;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = self.config.placeholderColor;
    label.userInteractionEnabled = NO;
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = 15.5;
    label.backgroundColor = [[UIColor colorWithHexString:@"#42714A"] colorWithAlphaComponent:0.1];
    [self.pathStackView addArrangedSubview: label];
}

- (void)pathItemTapped:(UIButton *)sender {
    [self navigateToLevel:sender.tag];
}

- (void)navigateToLevel:(NSInteger)level {
    // 重置到指定层级
    if (level < self.selectedPath.count) {
        [self.selectedPath removeObjectsInRange:NSMakeRange(level, self.selectedPath.count - level)];
    }
    
    // 加载对应层级数据
    if (level == 0) {
        self.currentLevelData = self.dataSource;
    } else if (level == 1) {
        UPDataItem *firstItem = self.selectedPath[0];
        self.currentLevelData = firstItem.children ?: @[];
    } else if (level == 2) {
        UPDataItem *secondItem = self.selectedPath[1];
        self.currentLevelData = secondItem.children ?: @[];
    }
    
    [self updatePathDisplay];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    
    // 通知代理
    if (level < self.selectedPath.count) {
        UPDataItem *item = self.selectedPath[level];
        if ([self.delegate respondsToSelector:@selector(addressPicker:didSelectItem:atLevel:)]) {
            [self.delegate addressPicker:self didSelectItem:item atLevel:level];
        }
    }
}

- (void)selectionComplete {
    if ([self.delegate respondsToSelector:@selector(addressPicker:didCompleteSelection:)]) {
        [self.delegate addressPicker:self didCompleteSelection:[self.selectedPath copy]];
    }
}

- (void)confirmButtonAction:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(addressPicker:didClickConfirmButton:)]) {
        [self.delegate addressPicker:self didClickConfirmButton:[self.selectedPath copy]];
    }
}

#pragma mark - UITableView DataSource & Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.currentLevelData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    UPDataItem *item = self.currentLevelData[indexPath.row];
    
    cell.textLabel.text = item.name;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.backgroundColor = [UIColor clearColor];
    
//    if (item.isLeaf || (self.maxLevel == 2 && self.selectedPath.count == 1)) {
//        cell.accessoryType = UITableViewCellAccessoryNone;
//    } else {
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UPDataItem *item = self.currentLevelData[indexPath.row];
    
    // 更新选择路径
    if (self.selectedPath.count > self.maxLevel - 1) {
        [self.selectedPath removeObjectsInRange:NSMakeRange(self.maxLevel - 1, self.selectedPath.count - (self.maxLevel - 1))];
    }
    [self.selectedPath addObject:item];
    
    if (item.isLeaf || self.selectedPath.count == self.maxLevel) {
        // 选择完成
        [self updatePathDisplay];
        [self selectionComplete];
    } else {
        // 加载下一级数据
        if (item.children && item.children.count > 0) {
            self.currentLevelData = item.children;
            [self updatePathDisplay];
            [self.tableView reloadData];
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
    }
    
    // 通知代理
    if ([self.delegate respondsToSelector:@selector(addressPicker:didSelectItem:atLevel:)]) {
        [self.delegate addressPicker:self didSelectItem:item atLevel:self.selectedPath.count - 1];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 48;
}

#pragma mark - Lazy Properties

- (UIScrollView *)pathScrollView {
    if (!_pathScrollView) {
        _pathScrollView = [[UIScrollView alloc] init];
        _pathScrollView.showsHorizontalScrollIndicator = NO;
        _pathScrollView.alwaysBounceHorizontal = YES;
    }
    return _pathScrollView;
}

- (UIStackView *)pathStackView {
    if (!_pathStackView) {
        _pathStackView = [[UIStackView alloc] init];
        _pathStackView.axis = UILayoutConstraintAxisHorizontal;
        _pathStackView.alignment = UIStackViewAlignmentFill;
        _pathStackView.distribution = UIStackViewDistributionFill;
        _pathStackView.spacing = 4;
    }
    return _pathStackView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorInset = UIEdgeInsetsMake(0, 16, 0, 16);
    }
    return _tableView;
}

//- (UILabel *)titleLabel {
//    if (!_titleLabel) {
//        _titleLabel = [[UILabel alloc] init];
//        _titleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
//        _titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
//        _titleLabel.textAlignment = NSTextAlignmentCenter;
//        _titleLabel.text = LocalizableForKey(@"Address Selection");
//    }
//    return _titleLabel;
//}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style1"] forState: UIControlStateNormal];
        [_confirmButton setTitle:LocalizableForKey(@"Confirm") forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

@end
